package com.cn.por.util.fastDFS;

import com.github.tobato.fastdfs.domain.fdfs.FileInfo;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class FSStoreGenericManagerImpl implements FSManager {
	@Autowired
	private FastFileStorageClient fastFileStorageClient;

	public FSEntity putObject(String bucket, FSEntity fsEntity) {
		String ext = FilenameUtils.getExtension(fsEntity.getName());
		StorePath storePath = this.fastFileStorageClient.uploadFile(bucket, fsEntity.getInputstream(),
				fsEntity.getSize(), ext);
		fsEntity.setKeyId(storePath.getPath());
		return fsEntity;
	}

	public FSEntity getObject(String bucket, String objectId) {
		objectId = bucket + "/" + objectId;
		StorePath storePath = StorePath.parseFromUrl(objectId);
		FileInfo fileInfo = this.fastFileStorageClient.queryFileInfo(storePath.getGroup(), storePath.getPath());
		InputStream inputStream = (InputStream) this.fastFileStorageClient.downloadFile(storePath.getGroup(),
				storePath.getPath(), new StreamDownloadCallback());
		FSEntity fsEntity = new FSEntity();
		fsEntity.setKeyId(objectId);
		fsEntity.setInputstream(inputStream);
		fsEntity.setSize(fileInfo.getFileSize());
		fsEntity.setName(objectId);
		fsEntity.setUpdatedate(null);
		fsEntity.setContentType(null);
		return fsEntity;
	}

	public boolean deleteObject(String bucket, String objectId) {
		objectId = bucket + "/" + objectId;
		this.fastFileStorageClient.deleteFile(objectId);
		return true;
	}

	public void setFastFileStorageClient(FastFileStorageClient fastFileStorageClient) {
		this.fastFileStorageClient = fastFileStorageClient;
	}

	public static class StreamDownloadCallback implements DownloadCallback<InputStream> {
		public InputStream recv(InputStream ins) throws IOException {
			return ins;
		}
	}
}
